/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <rom.prevot@gmail.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return R. Prevot
 * ----------------------------------------------------------------------------
 */

/******************************************************************************\
 *          ____                _______    _____ _             _              *
 *         |  _ \              |__   __|  / ____| |           | |             *
 *         | |_) | ___  _ __ _ __ | | ___| (___ | |_ ___   ___| | __          *
 *         |  _ < / _ \| '__| '_ \| |/ _ \\___ \| __/ _ \ / __| |/ /          *
 *         | |_) | (_) | |  | | | | | (_) |___) | || (_) | (__|   <           *
 *         |____/ \___/|_|  |_| |_|_|\___/_____/ \__\___/ \___|_|\_\          *
 *                                                                            *
\******************************************************************************/

package app.views;

import com.sun.awt.AWTUtilities;
import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
import org.jdesktop.core.animation.timing.Animator;
import org.jdesktop.core.animation.timing.AnimatorBuilder;
import org.jdesktop.core.animation.timing.TimingTarget;
import org.jdesktop.swingx.graphics.GraphicsUtilities;
import org.jdesktop.swingx.image.GaussianBlurFilter;
import org.jdesktop.core.animation.timing.PropertySetter;

/**
 *
 * @author PREVROMA
 */
public class APropos extends javax.swing.JFrame implements WindowListener {

    FadeIn animation;
    private BufferedImage blurBuffer;
    private BufferedImage backBuffer;
    private float alpha = 0.0f;

    /** Creates new form APropos */
    public APropos() {
        initComponents();
        this.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
        setSize(getWidth(), 150);
        this.setVisible(true);
        System.out.println("box: " + getWidth() + 'x' + getHeight());
        animation = new FadeIn(this);
        addWindowListener(this);
    }

    private void createBlur() {
        JRootPane root = SwingUtilities.getRootPane(this);
        blurBuffer = GraphicsUtilities.createCompatibleImage(
                getWidth(), getHeight());
        Graphics2D g2 = blurBuffer.createGraphics();
        root.paint(g2);
        g2.dispose();

        backBuffer = blurBuffer;

        blurBuffer = GraphicsUtilities.createThumbnailFast(
                blurBuffer, getWidth() / 2);
        blurBuffer = new GaussianBlurFilter(5).filter(blurBuffer, null);
    }

    @Override
    public void paintComponents(Graphics g) {
        if (isVisible() && blurBuffer != null) {
            Graphics2D g2 = (Graphics2D) g.create();

            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(backBuffer, 0, 0, null);

            g2.setComposite(AlphaComposite.SrcOver.derive(alpha));
            g2.drawImage(blurBuffer, 0, 0, getWidth(), getHeight(), null);
            g2.dispose();
        }
    }

    public float getAlpha() {
        return alpha;
    }

    public void setAlpha(float alpha) {
        this.alpha = alpha;
        repaint();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        btQuit = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jEditorPane1 = new javax.swing.JEditorPane();

        FormListener formListener = new FormListener();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("A propos");
        setAlwaysOnTop(true);
        setBackground(new java.awt.Color(51, 51, 51));
        setResizable(false);
        setUndecorated(true);

        jPanel1.setBackground(new java.awt.Color(51, 51, 51));
        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanel1.setMaximumSize(new java.awt.Dimension(352, 134));
        jPanel1.setMinimumSize(new java.awt.Dimension(352, 134));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/app/resources/Ghost.png"))); // NOI18N

        btQuit.setForeground(new java.awt.Color(204, 204, 204));
        btQuit.setText("x");
        btQuit.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        btQuit.setContentAreaFilled(false);
        btQuit.addActionListener(formListener);

        jLabel2.setForeground(new java.awt.Color(204, 204, 204));
        jLabel2.setText("Auteur:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setForeground(new java.awt.Color(204, 204, 204));
        jLabel3.setText("R. PREVOT");

        jLabel4.setForeground(new java.awt.Color(204, 204, 204));
        jLabel4.setText("Date: ");

        jLabel5.setForeground(new java.awt.Color(204, 204, 204));
        jLabel5.setText("Entre 2010 et 2012 (a peu près...)");

        jEditorPane1.setBackground(new java.awt.Color(51, 51, 51));
        jEditorPane1.setBorder(null);
        jEditorPane1.setForeground(new java.awt.Color(204, 204, 204));
        jEditorPane1.setText("BornToStock est un logiciel \nde gestion de stock  développé \npar R. Prevot pour BTR Narbonne");
        jEditorPane1.setAutoscrolls(false);
        jEditorPane1.setDisabledTextColor(new java.awt.Color(204, 204, 204));
        jEditorPane1.setEnabled(false);
        jEditorPane1.setRequestFocusEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(btQuit, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addComponent(jEditorPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btQuit)
                        .addGap(5, 5, 5)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jEditorPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == btQuit) {
                APropos.this.btQuitActionPerformed(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    private void btQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btQuitActionPerformed
        windowClosing(null);
    }//GEN-LAST:event_btQuitActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btQuit;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

    @Override
    public void windowOpened(WindowEvent e) {}

    @Override
    public void windowClosing(WindowEvent e) {
        if (this.animation != null) {
            this.animation.interrupt();
        }
        try {
            FadeOut f = new FadeOut(this);
            f.join(1000);
        } catch (InterruptedException ex) {
            //@todo something here?
            System.out.println("Erreur dégueu");
        }
    }

    @Override
    public void windowClosed(WindowEvent e) {}

    @Override
    public void windowIconified(WindowEvent e) {}

    @Override
    public void windowDeiconified(WindowEvent e) {}

    @Override
    public void windowActivated(WindowEvent e) {}

    @Override
    public void windowDeactivated(WindowEvent e) {}

    public class FadeIn extends Thread {

        APropos box;
        int width;
        int height;
        int x;
        int y;
        int destX;
        int destY;
        private boolean interrupted = false;

        public FadeIn(APropos box) {
            this.box = box;

            Toolkit kit = getToolkit();
            Dimension screenSize = kit.getScreenSize();
            Insets insets = kit.getScreenInsets(getGraphicsConfiguration());
            width = box.getWidth();
            height = box.getHeight();

            y = screenSize.height;
            x = (screenSize.width - insets.left - insets.right - width) / 2;
            destX = x;
            destY = (screenSize.height - insets.top - insets.bottom - height) / 2;
            
            System.out.println("Screen size: " + screenSize.width + "x" + screenSize.height);
            System.out.println("Box size: " + width + "x" + height);

            box.setBounds(x, y, width, height);

            start();
        }

        /**
         * Interrupt the thread
         */
        public void interrupt() {
            interrupted = true;
        }

        @Override
        public void run() {
            float d = y - destY;
            while (y >= destY && !interrupted) {
                float ratio = 1.0f - ((float) (y - destY) / d);
                AWTUtilities.setWindowOpacity(box, ratio);

                y--;
                box.setBounds(x, y, width, height);

                //box.repaint();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                }
            }
            Double dX;
            int iX;
            for (int i = 0; i <= 20; i++) {
                dX = Math.cos(i);
                iX = (int) (dX * 5);
                box.setBounds(x + iX, y, width, height);
                //AWTUtilities.setWindowOpacity(box, Math.abs(dX.floatValue()));
                try {
                    Thread.sleep(5);
                } catch (InterruptedException ex) {
                }
            }
        }
    }

    public static void main(String[] args) {
        new APropos();
    }
    
    public class FadeOut extends Thread{
        APropos box;
        
        boolean interrupted = false;
        
        float ratio = 1.0f;

        public FadeOut(APropos box) {
            this.box = box;
            
            start();
        }
        
        public void interrupt() {
            interrupted = true;
        }

        @Override
        public void run() {
            while (ratio > 0.f && !interrupted) {
                
                AWTUtilities.setWindowOpacity(box, ratio);
                ratio -= 0.01f;
                try {
                    Thread.sleep(5);
                } catch (InterruptedException ex) {
                }
            }
            
            box.dispose();
        }        
    }
}
